const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');
const moment = require('moment');
const config = require('../config');

//同步创建目录
function mkdirsSync(dir) {
    if (fs.existsSync(dir)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dir))) {
            fs.mkdirSync(dir);
            return true;
        }
    }
}

//获取文件扩展名
function getSuffixName(fileName) {
    let nameList = fileName.split('.')
    return nameList[nameList.length - 1];
}

//文件上传
function uploadFile(ctx, options) {
    let busboy = new Busboy({ headers: ctx.req.headers });
    let param = Object.assign(config.upload, options);
    let date = moment().format('YYYYMMDD');
    let fileType = param.fileType;
    let filePath = param.filePath;
    filePath = path.join(filePath, fileType, date);

    return new Promise((resolve, reject) => {

        console.log('开始上传');
        let result = {
            success: false,
            msg: '',
            data: null
        }

        if (!mkdirsSync(filePath)) {
            result.msg = '创建目录失败';
            resolve(result);
        }

        // 解析请求文件事件
        busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
            let fileName = Math.random().toString(16).substr(2) + '.' + getSuffixName(filename);
            let uploadFilePath = path.join(filePath, fileName);
            let savePath = path.join(uploadFilePath);

            // 文件保存到制定路径
            file.pipe(fs.createWriteStream(savePath));

            // 文件写入事件结束
            file.on('end', function() {
                result.success = true;
                result.msg = '文件上传成功';
                result.data = {
                    src: `uploads/${fileType}/${date}/${fileName}`
                }
                resolve(result);
            })
        })

        // 解析结束事件
        busboy.on('finish', function() {
            resolve(result);
        })

        // 解析错误事件
        busboy.on('error', function(err) {
            reject(result);
        })

        ctx.req.pipe(busboy);

    })


}
module.exports = uploadFile;